package com.taiyi.crm.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.taiyi.crm.mapper.PermissionMapper;
import com.taiyi.crm.pojo.entity.Permission;
import com.taiyi.crm.pojo.vo.LayUISelectMVO;
import com.taiyi.crm.service.IPermissionService;
import com.taiyi.crm.util.LayUITableResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class PermissionServiceImpl implements IPermissionService {
    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public LayUITableResult list(Integer page, Integer limit, Permission permission) {
        //1、使用PageHelper插件设置分页
        PageHelper.startPage(page, limit);
        // int offset = (page - 1) * limit;
        //2、执行查询
        List<Permission> list = permissionMapper.selectByPage(permission);
        //3、使用PageInfo对结果进行包装
        PageInfo pageInfo = new PageInfo(list);
        Integer count = (int) pageInfo.getTotal();//得到总数量

        return  LayUITableResult.ok(count, list);
    }

    @Override
    public void deleteById(Integer id) {

        permissionMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void deleteAll(String ids) {
        String[] idArray = ids.split(",");
        permissionMapper.deleteAll(idArray);
    }

    @Override
    public void insert(Permission permission) {
        int count = permissionMapper.insert(permission);
    }

    @Override
    public Permission selectByPrimaryKey(Integer permissionId) {
        return permissionMapper.selectByPrimaryKey(permissionId);
    }

    @Override
    public List<LayUISelectMVO> selectAllPermisssions() {
        // pageList没有传递任何参数，相当于查找所有
        List<Permission> permissions =
                permissionMapper.selectByPage(new Permission());
        // SelectM需要的结构[{"id":12,"name":"长者","status":0},{"id":11,"name":"长者1","status":1}]，
        // status就是选中和不选中状态
        // 所以在这里转换一下
        List<LayUISelectMVO> list = new ArrayList<>();
        for (Permission permission : permissions) {
            LayUISelectMVO layUISelectMVO = new LayUISelectMVO();
            layUISelectMVO.setId(permission.getId());
            layUISelectMVO.setName(permission.getName());
            layUISelectMVO.setStatus(1);
            list.add(layUISelectMVO);
        }

        return list;
    }

    @Override
    public List<Permission> selectByUserId(Integer id) {
        return permissionMapper.selectByUserId(id);
    }

}